<template>
    <div class="cate-search">
        <categorySearch ref="Search"/>
        <a-spin :spinning="spinning" size="large" tip="Loading...">
            <div class="main-box">
                <div class="left-box">
                    <div class="tit">图书分类目录</div>
                    <div class="tree-box">
                        <a-tree show-line :treeData="treeData" @select="onSelect" :defaultExpandedKeys="['0']" :selectedKeys="selectedKeys"></a-tree>
                    </div>
                </div>
                <div class="right-content">
                    <resultList :resultData="resultData" :rowCount="rowCount" :filters="filters" :sort.sync="sort" :disableSortScore="disableSortScore" @sortChange="normalSearch" />
                </div>
            </div>
            <div class="main-box">
                <a-pagination show-size-changer show-quick-jumper :current="pageth" :page-size="pageSize" :total="rowCount" :page-size-options="pageSizeOptions" @showSizeChange="onShowSizeChange" @change="onChange" />
            </div>
        </a-spin>
        <a-modal v-model="visibleUser" :closable="false" :keyboard="false" :maskClosable="false" width="20%" title="消息" @ok="login">
            <template slot="footer"><a-button key="submit" type="primary" @click="ConfirmError">确认</a-button></template>
            <p class="failure">获取用户信息出错，请联系管理员！</p>
        </a-modal>
        <a-modal v-model="visibleLook" :closable="false" :keyboard="false" :maskClosable="false" width="20%" title="消息" @ok="logout">
            <template slot="footer"><a-button key="submit" type="primary" @click="logout">确认</a-button></template>
            <p class="failure">您无权访问此站点！</p>
        </a-modal>
    </div>
</template>

<script>
    import axios from 'axios'
    import classesData from '../../utils/classesData.js'
    import categorySearch from '../../components/layout/categorySearch'
    import resultList from '../../components/resultList'
    import { instanceSearch, reportQuery, accountAuthtication } from '../../api/urls.js'
    export default {
        components:{
            categorySearch,
            resultList,
        },

        data(){
            return{
                visibleLook: false,
                visibleUser: false,
                spinning: true,
                freetext: '',
                treeData: classesData.treeData,
                resultData: [],
                rowCount: 0,
                sortScore: '1', // 无:'' , 升序:'0' , 降序:'1'
                sortTitle: '', // 无:'' , 升序:'0' , 降序:'1'
                sortPerson: '', // 无:'' , 升序:'0' , 降序:'1'
                sort: { field: "score", order: "desc" }, // score title person
                disableSortScore: false,
                selectedKeys: [],
                filters: [],
                secondCdtn: '',
                secondList: [],
                // 检索埋点字段
                query: "",
                filterQueries: [],
                actionType: "", // 按钮检索/CLC检索
                pageth: 1,
                pageSize: 10, // 每页显示几条 
                pageSizeOptions: ['10', '20', '30', '40', '50'],
            }
        },

        created() {
            this.checkUser()
            this.checkKeywords()
            this.originSearch(this.freetext)
        },

        mounted() {
            
        },

        methods:{
            // 是否显示关键词相关度排序
            checkKeywords() {
                if (this.freetext || this.secondCdtn) {
                    this.sort.field = "score";
                    this.sort.order = "desc";
                    this.disableSortScore = false;
                } else {
                    this.sort.field = "title";
                    this.sort.order = "asc";
                    this.disableSortScore = true;
                }
            },
            // 原始检索
            originSearch(freetext) {
                this.spinning = true
                this.freetext = freetext
                this.checkKeywords()
                let opts = {
                    freetext: freetext,
                    sorts: {
                        field: this.sort.field,
                        type: this.sort.order === "asc" ? "0" : "1",
                    },
                    pager: {
                        pageth: 1,
                        pageSize: 10
                    }
                }
                this.selectedKeys = []
                this.secondCdtn = '',
                this.secondList = [],
                this.filters = []
                this.pageth = 1
                this.pageSize = 10
                this.addFilter('freetext','搜索词', freetext)
                this.getResultData(opts)

                // 检索埋点（按钮检索）START
                this.query = ""
                this.filterQueries = []
                this.actionType = "按钮检索"
                if(this.freetext) {
                    this.query += "AND freetext:'"+this.freetext+"'"
                }
                // this.buryingPoint()
                // 检索埋点（按钮检索）END
            },

            // 常规检索
            normalSearch() {
                this.spinning = true
                let opts = {
                    freetext: this.freetext,
                    cdtn: [
                        // 分类
                        {
                            logic: 'and',
                            field:'FL', 
                            value:this.selectedKeys[0]||'',
                            type:'5'
                        }
                    ],
                    // 二次检索
                    secondCdtn: this.secondCdtn,
                    // 排序
                    sorts: {
                        field: this.sort.field,
                        type: this.sort.order === "asc" ? "0" : "1",
                    },
                    // 页码
                    pager: {
                        pageth: this.pageth,
                        pageSize: this.pageSize,
                    }
                }
                this.getResultData(opts)
            },

            // 分类浏览
            onSelect(selectedKeys, info) {
                this.spinning = true
                if(selectedKeys.length<=0&&this.selectedKeys || selectedKeys!=this.selectedKeys) {
                    for (var i = 0; i < this.filters.length; i++) {
                        if (this.filters[i].type == "selectedKeys") {
                            this.filters.splice(i, 1);
                        }
                    }
                }
                this.selectedKeys = selectedKeys
                this.addFilter('selectedKeys', '分类', info.node.$props.dataRef.title||'')
                this.pageth = 1
                this.pageSize = 10
                this.checkKeywords()
                this.normalSearch()

                // 检索埋点（CLC检索） START
                this.query = ""
                this.filterQueries = []
                this.actionType = "CLC检索"
                if(this.freetext) {
                    this.query += "AND freetext:'"+this.freetext+"' "
                }
                if(this.selectedKeys[0]) {
                    this.query += "AND FL:'"+this.selectedKeys[0]+"' "
                }
                // this.buryingPoint()
                // 检索埋点（CLC检索） END
            },

            addFilter(type,title,value){
                if(value) {
                    this.filters.push({type,title,value})
                }
            },

            onChange(pageth, size) {
                this.pageth = pageth
                this.pageSize = size
                this.normalSearch()
            },

            onShowSizeChange(current, size) {
                this.pageSize = size
                this.normalSearch()
            },

            secondSearch() {
                this.checkKeywords()
                this.normalSearch()
                // 检索埋点（CLC检索） START
                this.query = ""
                this.filterQueries = []
                this.actionType = "按钮检索"
                if(this.freetext) {
                    this.query += "AND freetext:'"+this.freetext+"' "
                }
                if(this.selectedKeys[0]) {
                    this.query += "AND FL:'"+this.selectedKeys[0]+"' "
                }
                this.filterQueries = [this.secondCdtn]
                // this.buryingPoint()
                // 检索埋点（CLC检索） END
            },

            async getResultData(opts) {
                // await axios.post("api/instance/search", opts).then(response => {
                await axios.post(instanceSearch, opts).then(response => { // chenss 20240327
                    if (response.data.success) {
                        this.resultData = response.data.data.resultList
                        this.rowCount = response.data.data.pager.rowCount
                        this.spinning = false
                    } else {
                        this.$message.error("System Error")
                    }
                });
            },

            // 检索埋点
            async buryingPoint() {
                await axios.post(reportQuery, {
                    pieceTypeId: 1,
                    products: [],
                    facets: [],
                    token: sessionStorage.getItem('token'),
                    query: this.query,
                    filterQueries: this.filterQueries,
                    actionType: this.actionType,
                    sourceType: "文献导航",
                    searchType: "FUZZY",
                }).then(response => {
                    if (response.data.status==0) {
                        // 成功
                    } else {
                        // 失败
                    }
                });
            },

            async checkUser() {
                this.$parent.$parent.spinner = true
                /* 
                判断是否有传入token
                登录：https://www.cnbksy.com/jdLogin?targetUrl=https://tushu.cnbksy.com?ss
                返回token：https://jdts.library.sh.cn/?ss&token=6fd70427739110ab86b4a2f427423bb2e0c1cc2707665536f676fb4dda7a7ff6af8503d1c564ea39f86392a3848ec58ee7590403f3aee5947c0f9838e5f61396#/
                router(路由配置) 需修改为 mode: 'history' 模式
                通过 this.$route.query.xxx 获取
                */
                if(!sessionStorage.getItem('token')) {
                    sessionStorage.setItem('token', this.$route.query.token||'')
                }
                if(sessionStorage.getItem('token')&&!sessionStorage.getItem('orgName')) {
                    await axios.post(`${accountAuthtication}?token=`+ sessionStorage.getItem('token')).then(response => {
                        // debugger
                        if (response.data.result==0) {
                            this.$parent.$parent.$refs.header.orgName = response.data.data.username
                            sessionStorage.setItem('orgName', response.data.data.username)
                            this.$router.push({name: 'categorySearch'})
                        } else {
                            this.visibleUser = true
                        }
                    });
                }
                if(sessionStorage.getItem('token')) {
                    this.$router.push({name: 'categorySearch'})
                    // location.reload()
                }
                this.$parent.$parent.spinner = false
            },

            ConfirmError(){
                this.visibleUser = false
            },
            login() {
                window.location = 'https://dhapi.library.sh.cn/management/webapi/cenofmagent/token/locpage?systemId=20&durl=https://jdts.library.sh.cn/index'
            },

            async logout() {
                this.$parent.$parent.spinner = true
                this.visibleLook = false
                sessionStorage.setItem('token', '')
                sessionStorage.setItem('orgName', '')
                this.$router.push({
                    name: 'advanceSearch'
                })
                location.reload()
            },


            quit() {
                window.opener = null;
                window.open("about:blank", "_self").close()
            },

        }
    }
</script>

<style lang="less" scoped>
    .ant-btn-primary {
        background-color: #661112;
        border-color: #661112;
    }
</style>

<style lang="less">
    .ant-tree-switcher,.ant-tree-title {
        font-size: 1.1rem;
    }
</style>
